package com.woniu.his.mms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.his.bms.client.BillRecordClient;
import com.woniu.his.bms.client.result.BillRecordResult;
import com.woniu.his.exception.HisException;
import com.woniu.his.mms.common.MmsResultCode;
import com.woniu.his.mms.common.MmsStatusEnum.MmsStatusCode;
import com.woniu.his.mms.infra.model.Drug;
import com.woniu.his.mms.infra.model.MedicineItemRecord;
import com.woniu.his.mms.infra.model.MedicinePrescriptionRecord;
import com.woniu.his.mms.infra.mapper.MedicinePrescriptionRecordMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.his.mms.service.DrugService;
import com.woniu.his.mms.service.MedicineItemRecordService;
import com.woniu.his.mms.service.MedicinePrescriptionRecordService;
import com.woniu.his.mms.service.dto.MedicineItemDto;
import com.woniu.his.mms.service.dto.MedicinePrescriptionDto;
import com.woniu.his.mms.service.param.CreateMedicineServiceParam;
import com.woniu.his.mms.service.param.DmsMedicineItemRecordServiceParam;
import com.woniu.his.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 成药处方记录表 服务实现类
 * </p>
 *
 * @author ZJH
 * @since 2022-11-28
 */
@Service
@Slf4j
public class MedicinePrescriptionRecordServiceImpl extends ServiceImpl<MedicinePrescriptionRecordMapper, MedicinePrescriptionRecord> implements MedicinePrescriptionRecordService {


    @Resource
    private DrugService drugService;

    @Resource
    private MedicineItemRecordService medicineItemRecordService;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private BillRecordClient billRecordClient;

    /**
     * 开立处方
     * @param param1
     * @return
     */
    @Override
    public Long applyMedicine(CreateMedicineServiceParam param1) {

        List<DmsMedicineItemRecordServiceParam> dmsMedicineItemRecordList = param1.getDmsMedicineItemRecordList();
        List<Long> ids = dmsMedicineItemRecordList.stream().map(DmsMedicineItemRecordServiceParam::getDrugId).collect(Collectors.toList());
        List<Drug> drugs = drugService.listByIds(ids);
        if(drugs==null||drugs.size()<=0) throw  new HisException(MmsResultCode.DRUG_NOT_EXIST);
        BigDecimal Amount = new BigDecimal("0");
        for (Drug drug : drugs) {
            for (DmsMedicineItemRecordServiceParam dmsMedicineItemRecordServiceParam : dmsMedicineItemRecordList) {
                if(dmsMedicineItemRecordServiceParam.getDrugId()==drug.getId()){
                    BigDecimal multiply = drug.getPrice().multiply(BigDecimal.valueOf(dmsMedicineItemRecordServiceParam.getNum()));
                    Amount=Amount.add(multiply);
                }
            }
        }
        //先生成处方记录
        MedicinePrescriptionRecord medicinePrescriptionRecord = BeanUtil.copyProperties(param1, MedicinePrescriptionRecord.class);
        medicinePrescriptionRecord.setMedicinePrescriptionStatus(MmsStatusCode.MEDICINE_PRESCRIPTION_STATUS_NOT_PAY.getCode());
        medicinePrescriptionRecord.setCreateTime(new Date());
        medicinePrescriptionRecord.setAmount(Amount);
        medicinePrescriptionRecord.setRefundStatus("NOT_REFUND");


        //生成账单
        Result<BillRecordResult> result = billRecordClient.createBillRecord("MEDICINE",Amount ,param1.getCaseHistoryId());
        medicinePrescriptionRecord.setBillId(result.getData().getId());
        medicinePrescriptionRecord.setBillId(result.getData().getId());
        save(medicinePrescriptionRecord);
        //生成药方详情
        MedicineItemRecord medicineItemRecord = new MedicineItemRecord();
        for (DmsMedicineItemRecordServiceParam dmsMedicineItemRecordServiceParam : dmsMedicineItemRecordList) {
            MedicineItemRecord medicineItemRecord1 = BeanUtil.copyProperties(dmsMedicineItemRecordServiceParam, MedicineItemRecord.class);
            medicineItemRecord1.setMedicineItemStatus(MmsStatusCode.ITEM_STATUS_NOT_TAKE.getCode());
            medicineItemRecord1.setPrescriptionId(medicinePrescriptionRecord.getId());
            medicineItemRecordService.save(medicineItemRecord1);
        }
        System.out.println(medicinePrescriptionRecord.toString());

        //存入redis
        RBucket<Object> bucket = redissonClient.getBucket("MedicinePrescription:" + param1.getCaseHistoryId());
        bucket.set(medicinePrescriptionRecord);
        return medicinePrescriptionRecord.getId();
    }

    /**
     * 作废药方
     * @param ids
     * @return
     */
    @Override
    public boolean invalidMedicine(List<Long> ids) {
        List<MedicinePrescriptionRecord> medicinePrescriptionRecords = listByIds(ids);
        for (MedicinePrescriptionRecord medicinePrescriptionRecord : medicinePrescriptionRecords) {
            medicinePrescriptionRecord.setMedicinePrescriptionStatus(MmsStatusCode.MEDICINE_PRESCRIPTION_STATUS_DELETE.getCode());
            RBucket<Object> bucket = redissonClient.getBucket("MedicinePrescription:" + medicinePrescriptionRecord.getCaseHistoryId());
            log.info("开始删除redis 中的西药处方:{}",bucket.get());
            bucket.delete();
        }
        updateBatchById(medicinePrescriptionRecords);
        QueryWrapper<MedicineItemRecord> wrapper = new QueryWrapper<>();
        wrapper.in("prescription_id",ids);
        wrapper.eq("medicineItem_status",MmsStatusCode.HERBAL_ITEM_STATUS_NOT_FINISHED.getCode());
        List<MedicineItemRecord> list = medicineItemRecordService.list(wrapper);
        for (MedicineItemRecord medicineItemRecord : list) {
            medicineItemRecord.setMedicineItemStatus("DELETE");

        }
        boolean b = medicineItemRecordService.updateBatchById(list);
        return b;
    }

    @Override
    public MedicinePrescriptionDto queryMedicinePrescriptionByBillId(Long BillId) {
        MedicinePrescriptionRecord record = getOne(new QueryWrapper<MedicinePrescriptionRecord>().eq("bill_id", BillId));
        if(record==null) throw new HisException(MmsResultCode.PRESCRIPTION_NOT_EXISTS);
        List<MedicineItemRecord> itemRecords = medicineItemRecordService.list(new QueryWrapper<MedicineItemRecord>().eq("prescription_id", record.getId()));
        MedicinePrescriptionDto medicinePrescriptionDto = BeanUtil.copyProperties(record, MedicinePrescriptionDto.class);
        List<MedicineItemDto> medicineItemDtos = BeanUtil.copyToList(itemRecords, MedicineItemDto.class);
        medicinePrescriptionDto.setMedicineItemDtos(medicineItemDtos);
        return medicinePrescriptionDto;
    }

    @Override
    public Boolean paySuccess(Long billId) {
        MedicinePrescriptionRecord medicinePrescriptionRecord = getOne(new QueryWrapper<MedicinePrescriptionRecord>().eq("bill_id",billId));
        medicinePrescriptionRecord.setMedicinePrescriptionStatus(MmsStatusCode.MEDICINE_PRESCRIPTION_STATUS_PAID.getCode());
        updateById(medicinePrescriptionRecord);
        return true;
    }
}
